import {h, init} from 'snabbdom'
import style from 'snabbdom/modules/style'
import eventlisteners from 'snabbdom/modules/eventlisteners'

const patch = init([style, eventlisteners]);

// 页面容器
let app = document.getElementById('app');

// 初始化数据
let data = new Array(10).fill(0).map((_, i) => i).map(index => ({
  index,
  content: randomMovie(),
}));

// 保存 vnode
let vnode = initVnode(data);

// 首次渲染
patch(app, vnode);

// 得到页面需要渲染的 vnode
function initVnode (data) {
  return h('div.wrap', {
    style: {
      width: '800px',
      margin: '100px auto',
      padding: '20px',
    }
  }, [
    h('div.toolBtn',{
      style:{
        marginBottom: '20px',
        textAlign: 'center'
      }
    },  
    [
      h('span', '排序操作：'),
      h('button', { style: { 'margin-right': '10px' }, on: { click: [btnClickHandle, 'up'] } }, 'up'),
      h('button', { style: { 'margin-right': '10px' }, on: { click: [btnClickHandle, 'down'] } }, 'down'),
      h('button', { style: { 'margin-right': '10px' }, on: { click: [btnClickHandle, 'random'] } }, 'random'),
      h('button', { on: { click: [btnClickHandle, 'add'] } }, 'add')
    ]),
    h('div.content', {
      style: {
        lineHeight: '2em'
      }
    },data.map(getChildVnode))
  ]);
}


// 渲染页面
function render (data) {
  vnode = patch(vnode, initVnode(data))
}

// 随机电影名组合
function randomMovie() {
  const data = ['1917', '歇菜', '寄生虫', '魅影缝匠', '饥饿站台', '叔·叔']
  let str = ''
  for (let i = 0, len = data.length; i < len; i++) {
    let movie = data[Math.floor(Math.random() * len)]
    i > 0 ? str += '-' + movie : movie
  }
  return str;
}

// 子元素
function getChildVnode(item) {
  return h('div', [
    h('span', item.index),
    h('span', item.content),
    h('span', {
      key: item.content,
      on: {
        click: [removeHandle, item.index]
      },
      style: {
        cursor: 'pointer',
        display: 'inline-block',
        padding: '10px'
      }
    }, 'X')
  ])
}
const btnFn = {
  upHandle,
  downHandle,
  randomHandle,
  addHandle
}
function btnClickHandle (type) {  
  const fn = type+'Handle'
  console.log(fn)
  btnFn[fn] && btnFn[fn]()
  render(data)
}
// 升序
function upHandle () {
  data.sort((a, b) => a.index - b.index);
}
// 降序
function downHandle () {
  data.sort((a, b) => b.index - a.index);
}
// 随机
function randomHandle () {
  data.sort(() => Math.random() > 0.5 ? -1 : 1)
}
// 添加一项
function addHandle () {
  const total = data.length;
  const item = {
    index: total,
    content: randomMovie(),
  };
  data.unshift(item);
}

function removeHandle (index) {
  // vnode = initVnode(data);
  for (let i = 0, len = data.length; i < len;i++ ) {
    if (data[i]['index'] === +index) {
      data.splice(i, 1);
      break
    }
  }
  render(data);
}

